//
//  ViewController1.m
//  BarCodeAndQRCode
//
//  Created by jiezsoft.com on 14-10-10.
//  Copyright (c) 2014年 jiezsoft.com. All rights reserved.
//
#import "ScanViewController.h"
#import "UIViewExt.h"
#import "HttpRequest.h"
#import "RDVTabBarController.h"
#import "MembershipDetailsViewController.h"
#import "UIViewExt.h"
#import "HttpRequest.h"
#import "InventoryViewController.h"
#import "RDVTabBarController.h"
#import "OrderDetailViewController.h"
#import "PreviewView.h"
#import "CouponCheckViewController.h"
@interface ScanViewController ()<UIGestureRecognizerDelegate,UINavigationControllerDelegate,UITextFieldDelegate,InventoryViewControllerDelegate,CouponCheckViewControllerDelegate>
@end
@implementation ScanViewController
{   PreviewView*Preview;
    double d;
    int d1;
    NSString*specName;
    UITextField*searchTextField;
    NSMutableArray* scanStockResultArray;
    NSMutableArray* itemUrlArray;
    NSMutableArray* itemTypeNameArray;
    NSMutableArray* itemSeriesNameArray;
    NSMutableArray* itemInDateArray;
    NSMutableArray* itemWeightArray;
    NSMutableArray* itemPriceArray;
    NSMutableArray* currentSpecIdArray;
    NSMutableArray* itemNameArray;
    NSMutableArray* itemidArray;
    NSMutableArray* itemCodeArray;
    NSMutableArray* howArray;
    NSMutableArray* specNameArray;
    NSMutableArray* titleCouponArray;
    NSMutableArray* priceCouponArray;
    NSMutableArray* beginDateCouponArray;
    NSMutableArray* qtyCouponArray;
    NSMutableArray* imageUrlCouponArray;
    NSMutableArray* endDateCouponArray;
    NSMutableArray* useLimitAmtCouponArray;
    NSMutableArray* couponIdArray;
    NSMutableArray* snArray;
    UIButton *SCANSTOCK;
    UIButton *SCANSTOCK1;
    UIButton *numberSCANSTOCK1;
    BOOL no;
    UIButton*theLampBtn;
    UIView*menuBarView;
    UIView*menuBarViewTming;
    UIButton*backButton;
    UIView*searchView;
    NSArray*nameBtn;
    NSArray*arrayimage;
    NSArray*arrayimage1;
    NSString* Token;
}
@synthesize alt = alt;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
    }
    return self;
}
-(void)BackAction:(UIButton *)sender{
    [Preview.line removeFromSuperview];
    [[self rdv_tabBarController]setSelectedIndex:0];
}
- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    [Preview.line removeFromSuperview];
    self.navigationController.delegate = nil;
}
- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    }
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController.navigationBar setTintColor:[UIColor whiteColor]];
    [[UINavigationBar appearance] setBarTintColor:Color];
    self.navigationItem.rightBarButtonItem = nil;
    self.navigationController.navigationBarHidden=YES;
    [[self rdv_tabBarController] setTabBarHidden:YES];
    UIBarButtonItem* barbuttonitem=[[UIBarButtonItem alloc]init];
    barbuttonitem.title=@"";
    barbuttonitem.tintColor=[UIColor whiteColor];
    [barbuttonitem setTintColor:[UIColor whiteColor]];
    self.navigationItem.backBarButtonItem=barbuttonitem;
    [self.navigationController.navigationBar setTintColor:[UIColor whiteColor]];
    [[UINavigationBar appearance] setBarTintColor:[UIColor whiteColor]];
    self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    self.navigationController.interactivePopGestureRecognizer.delegate = self;
  
    UILabel* prompt=[[UILabel alloc]initWithFrame:CGRectMake(0, ScreenHeight*380/1334,ScreenWidth,14)];
    prompt.text=@"对准条码或二维码，即可自动扫描";
    prompt.textColor=[UIColor colorWithRed:204/255.0 green:204/255.0 blue:204/255.0 alpha:1];
    prompt.textAlignment=NSTextAlignmentCenter;
    prompt.font=[UIFont systemFontOfSize:14];
    NSMutableAttributedString *AttributedStr1 = [[NSMutableAttributedString alloc]initWithString:@"对准条码或二维码，即可自动扫描"];
    [AttributedStr1 addAttribute:NSForegroundColorAttributeName
     
                           value:luseColor
     
                           range:NSMakeRange(2, 2)];
    [AttributedStr1 addAttribute:NSForegroundColorAttributeName
     
                           value:luseColor
     
                           range:NSMakeRange(5, 3)];
    prompt.attributedText = AttributedStr1;
    [self.view addSubview:prompt];
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    Token = [user objectForKey:@"tokenId"];

    
}
-(void)secondViewController:(CouponCheckViewController *)secondViewController titleCouponArray:(NSMutableArray *)titleCouponArrays  priceCouponArray:(NSMutableArray *)priceCouponArrays beginDateCouponArray:(NSMutableArray *)beginDateCouponArrays qtyCouponArray:(NSMutableArray *)qtyCouponArrays imageUrlCouponArray:(NSMutableArray *)imageUrlCouponArrays :(NSMutableArray *)endDateCouponArrays useLimitAmtCouponArray:(NSMutableArray *)useLimitAmtCouponArrays couponIdArray:(NSMutableArray *)couponIdArrays :(NSMutableArray *)snArrays{
    titleCouponArray=[titleCouponArrays mutableCopy];
    priceCouponArray=[priceCouponArrays mutableCopy];
    beginDateCouponArray = [beginDateCouponArrays mutableCopy];
    qtyCouponArray = [qtyCouponArrays mutableCopy];
    imageUrlCouponArray = [imageUrlCouponArrays mutableCopy];
    endDateCouponArray = [endDateCouponArrays mutableCopy];
    useLimitAmtCouponArray = [useLimitAmtCouponArrays mutableCopy];
    couponIdArray = [couponIdArrays mutableCopy];
    snArray = [snArrays mutableCopy];
    self.sat=@"0";
    [numberSCANSTOCK1 setTitle: [NSString stringWithFormat:@"%ld", titleCouponArrays.count] forState:UIControlStateNormal];
    [numberSCANSTOCK1 addTarget:self action:@selector(scanStockCountBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self requestData];
}

-(void)secondViewController:(InventoryViewController *)secondViewController itemCodeArray:(NSMutableArray *)itemCodeArrays scanStockResultArray:(NSMutableArray *)scanStockResultArrays itemUrlArray:(NSMutableArray *)itemUrlArrays howArray:(NSMutableArray *)howArrays itemPriceArray:(NSMutableArray *)itemPriceArrays currentSpecIdArray:(NSMutableArray *)currentSpecIdArrays itemNameArray:(NSMutableArray *)itemNameArrays itemidArray:(NSMutableArray *)itemidArrays specNameArray:(NSMutableArray *)specNameArrays{
            itemCodeArray=[itemCodeArrays mutableCopy];
            scanStockResultArray=[scanStockResultArrays mutableCopy];
            itemUrlArray = [itemUrlArrays mutableCopy];
            howArray = [howArrays mutableCopy];
            itemPriceArray = [itemPriceArrays mutableCopy];
            currentSpecIdArray = [currentSpecIdArrays mutableCopy];
            itemNameArray = [itemNameArrays mutableCopy];
            itemidArray = [itemidArrays mutableCopy];
            specNameArray = [specNameArrays mutableCopy];
            self.sat=@"1";
            NSNumber *sum = [howArray valueForKeyPath:@"@sum.floatValue"];
            [numberSCANSTOCK1 setTitle: [NSString stringWithFormat:@"%@", sum] forState:UIControlStateNormal];
            [numberSCANSTOCK1 addTarget:self action:@selector(scanStockCountBtnClick) forControlEvents:UIControlEventTouchUpInside];
            [self requestData];
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    self.sat=@"1";//商品参数
    _userNameStr=@"";
    itemCodeArray=[[NSMutableArray alloc]init];
    scanStockResultArray=[[NSMutableArray alloc]init];
    itemUrlArray=[[NSMutableArray alloc]init];
    itemTypeNameArray=[[NSMutableArray alloc]init];
    itemSeriesNameArray=[[NSMutableArray alloc]init];
    itemInDateArray=[[NSMutableArray alloc]init];
    currentSpecIdArray=[[NSMutableArray alloc]init];
    itemPriceArray=[[NSMutableArray alloc]init];
    itemidArray=[[NSMutableArray alloc]init];
    itemNameArray=[[NSMutableArray alloc]init];
    howArray=[[NSMutableArray alloc]init];
    specNameArray=[[NSMutableArray alloc]init];
    //核销券参数
    titleCouponArray=[[NSMutableArray alloc]init];
    priceCouponArray=[[NSMutableArray alloc]init];
    beginDateCouponArray=[[NSMutableArray alloc]init];
    qtyCouponArray=[[NSMutableArray alloc]init];
    imageUrlCouponArray=[[NSMutableArray alloc]init];
    endDateCouponArray=[[NSMutableArray alloc]init];
    useLimitAmtCouponArray=[[NSMutableArray alloc]init];
    couponIdArray=[[NSMutableArray alloc]init];
    snArray=[[NSMutableArray alloc]init];
    nameBtn=[[NSArray alloc]initWithObjects:@"核销券",@"扫记录",@"扫订单",nil];
    arrayimage = @[@"hexiaoquan_normal",@"saojilv_normal",@"saodingdan_normal"];
    arrayimage1 = @[@"hexiaoquan_hight",@"saojilv_hight",@"saodingdan_hight"];
    [self requestData];
}
-(void)requestData{
    [Preview removeFromSuperview];
    [timer invalidate];
    stringValue=@"";
    isDown=NO;
    num=0;
    _captureSession=nil;
    Preview = [[PreviewView alloc] initWithFrame:CGRectMake(0, 0,ScreenWidth,ScreenHeight)];
    [self.view addSubview:Preview];
    [self startRead];
    [self number];//库存记录数
    [self loadingMenuBar];//加载菜单栏
    d1=[[NSString stringWithFormat:@"%.f", ScreenWidth*460/750]intValue];
    if (d1==253) {
        d1=252;
    }
    if (d1==203) {
        d1=300;
    }
    if (d1==471) {
        d1=350;
    }
    timer = [NSTimer scheduledTimerWithTimeInterval:.02 target:self selector:@selector(lineAnimation) userInfo:nil repeats:YES];
    [self loadingtitle];
    
}

-(void)loadingMenuBar{
    [menuBarView removeFromSuperview];
    [menuBarViewTming removeFromSuperview];
    menuBarView=[[UIView alloc]initWithFrame:CGRectMake(0,   ScreenHeight-64, ScreenWidth, 64)];
    menuBarView.backgroundColor=[UIColor blackColor];
    menuBarView.alpha=0.66;
    [self.view addSubview:menuBarView];
    menuBarViewTming=[[UIView alloc]initWithFrame:CGRectMake(0,   ScreenHeight-64, ScreenWidth, 64)];
    menuBarViewTming.backgroundColor=[UIColor clearColor];
    [self.view addSubview:menuBarViewTming];
    for (int i = 0; i<3; i++) {
        UIButton *nameButcenter = [[UIButton alloc]initWithFrame:CGRectMake(ScreenWidth/3*i,   0, ScreenWidth/3, 50)];
        [nameButcenter addTarget:self action:@selector(btnTouchUpInsid:) forControlEvents:UIControlEventTouchUpInside];
        [menuBarViewTming addSubview:nameButcenter];
        nameButcenter.tag=i;
        UIButton *nameBut = [[UIButton alloc]initWithFrame:CGRectMake(ScreenWidth/3*i,   45, ScreenWidth/3, 12)];
        [nameBut setTitle: [nameBtn objectAtIndex:i]  forState:UIControlStateNormal];
        nameBut.tag=i;
        [nameBut setTitleColor:shenhuiColor forState:0];
        if (i==self.sat.intValue) {
            [nameBut setTitleColor:luseColor forState:0];
        }
        nameBut.titleLabel.font=[UIFont systemFontOfSize:12];
        [nameBut addTarget:self action:@selector(btnTouchUpInsid:) forControlEvents:UIControlEventTouchUpInside];
        [menuBarViewTming addSubview:nameBut];
        UIButton * nameBtnImage = [UIButton buttonWithType:UIButtonTypeCustom];
        nameBtnImage.frame = CGRectMake(ScreenWidth/3*i, 10, 30, 30);
        nameBtnImage.tag =i;
        nameBtnImage.center=nameButcenter.center;
        [nameBtnImage setBackgroundImage:[UIImage imageNamed: [arrayimage objectAtIndex:i]] forState:UIControlStateNormal];
        if (i==self.sat.intValue) {
            [nameBtnImage setBackgroundImage:[UIImage imageNamed: [arrayimage1 objectAtIndex:i]] forState:UIControlStateNormal];
        }
        [nameBtnImage addTarget:self action:@selector(btnTouchUpInsid:) forControlEvents:UIControlEventTouchUpInside];
        [menuBarViewTming addSubview:nameBtnImage];
    }

}

-(void)number{
   
        [SCANSTOCK removeFromSuperview];
        [SCANSTOCK1 removeFromSuperview];
        [numberSCANSTOCK1 removeFromSuperview];
        SCANSTOCK = [[UIButton alloc]initWithFrame:CGRectMake(ScreenWidth*290/750, ScreenHeight*980/1334, ScreenWidth* 160/750, ScreenWidth* 160/750)];
        SCANSTOCK.layer.masksToBounds = YES;
        SCANSTOCK.layer.cornerRadius = ScreenWidth* 160/750/2;
        SCANSTOCK.layer.borderColor = luseColor.CGColor;
        SCANSTOCK.layer.borderWidth = 0.5;
        SCANSTOCK.contentMode = UIViewContentModeScaleAspectFit;
        SCANSTOCK1 =[[UIButton alloc]initWithFrame:CGRectMake(290*ScreenWidth/750, ScreenHeight*1010/1334,ScreenWidth* 160/750, ScreenWidth* 160/750)];
        [SCANSTOCK1  setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        SCANSTOCK1.titleLabel.font = [UIFont systemFontOfSize:13];
        SCANSTOCK1.titleLabel.textAlignment = NSTextAlignmentCenter;
        numberSCANSTOCK1 =[[UIButton alloc]initWithFrame:CGRectMake(290*ScreenWidth/750, ScreenHeight*950/1334,ScreenWidth* 160/750, ScreenWidth* 160/750)];
        [numberSCANSTOCK1  setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        numberSCANSTOCK1.titleLabel.font = [UIFont systemFontOfSize:24];
        numberSCANSTOCK1.titleLabel.textAlignment = NSTextAlignmentCenter;
    
    if ([self.sat isEqualToString:@"0"]) {
        [numberSCANSTOCK1 setTitle: [NSString stringWithFormat:@"%ld", snArray.count] forState:UIControlStateNormal];
        [SCANSTOCK1 setTitle:@"已扫优惠券" forState:UIControlStateNormal];
         [numberSCANSTOCK1 addTarget:self action:@selector(scanCouponCountBtnClick) forControlEvents:UIControlEventTouchUpInside];
    }  if ([self.sat isEqualToString:@"1"]) {
        NSNumber *sum = [howArray valueForKeyPath:@"@sum.floatValue"];
        [numberSCANSTOCK1 setTitle: [NSString stringWithFormat:@"%@", sum] forState:UIControlStateNormal];
        [SCANSTOCK1 setTitle:@"已选商品" forState:UIControlStateNormal];
         [numberSCANSTOCK1 addTarget:self action:@selector(scanStockCountBtnClick) forControlEvents:UIControlEventTouchUpInside];
        
    }
        [self.view addSubview:SCANSTOCK];
        [self.view addSubview:SCANSTOCK1];
        [self.view addSubview:numberSCANSTOCK1];
       
    
}
-(void)OnTapDone{
    [searchTextField resignFirstResponder];
    if ([self.sat isEqualToString:@"0"]) {
        if (![snArray containsObject:searchTextField.text]) {
            stringValue = searchTextField.text;
            [self performSelectorOnMainThread:@selector(Coupon) withObject:nil waitUntilDone:NO];
        }else{
        }

    }
    if ([self.sat isEqualToString:@"2"]) {
        OrderDetailViewController *detailViewController = [[OrderDetailViewController alloc] init];
        detailViewController.orderId=searchTextField.text;
        [self.navigationController pushViewController:detailViewController animated:YES];
    }
    if ([self.sat isEqualToString:@"1"]) {
        if (![scanStockResultArray containsObject:searchTextField.text]) {
            stringValue = searchTextField.text;
            [self performSelectorOnMainThread:@selector(loadStockVC) withObject:nil waitUntilDone:NO];
        }else{
}
    }
}

- (void)navigationController:(UINavigationController *)navigationController
       didShowViewController:(UIViewController *)viewController
                    animated:(BOOL)animated
{
    if ([navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        navigationController.interactivePopGestureRecognizer.enabled = YES;
    }
}
-(void)theLampBtn{
    
    
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    if (![device hasTorch]) {
        NSLog(@"no torch");
    }else{
        [device lockForConfiguration:nil];
        no=!no;
        if (no) {
            [device setTorchMode: AVCaptureTorchModeOn];
            [theLampBtn setImage:[UIImage imageNamed:@"shanguangdeng_hight"] forState:UIControlStateNormal];
        }
        else
        {
            [device setTorchMode: AVCaptureTorchModeOff];
            [theLampBtn setImage:[UIImage imageNamed:@"shanguangdeng_normal"] forState:UIControlStateNormal];
        }
        [device unlockForConfiguration];
    }
    }
-(void)btnTouchUpInsid:(UIButton*)sender{
    if (sender.tag==0) {
       self.sat=@"0";
        [self number];
       [self loadingMenuBar];
}
    if (sender.tag==1) {
        self.sat=@"1";
        [self number];
        [self loadingMenuBar];
    }
    if (sender.tag==2) {
        [SCANSTOCK removeFromSuperview];
        [SCANSTOCK1 removeFromSuperview];
        [numberSCANSTOCK1 removeFromSuperview];
        self.sat=@"2";
        [self loadingMenuBar];
    }
}
-(void)lineAnimation
{
        if (isDown==NO) {
        num++;
        Preview.line.frame=CGRectMake(ScreenWidth*30/750, 2*num, ScreenWidth*600/750, 3);
        if (2*num==d1) {
            isDown=YES;
        }
    }
    else
    {
        num--;
        Preview.line.frame=CGRectMake(ScreenWidth*30/750, 2*num, ScreenWidth*600/750, 3);
        if (num==0) {
            isDown=NO;
        }
    }
    
}
-(BOOL)startRead
{
    NSError *error;
    AVCaptureDevice *captureDevice=[AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    AVCaptureDeviceInput *input=[AVCaptureDeviceInput deviceInputWithDevice:captureDevice error:&error];
    if (!input) {
        NSLog(@"%@", [error localizedDescription]);
        return NO;
    }
    _captureSession = [[AVCaptureSession alloc] init];
    if ([_captureSession canAddInput:input]) {
        [_captureSession addInput:input];
    }
    
    
    AVCaptureMetadataOutput *captureMetadataOutput = [[AVCaptureMetadataOutput alloc] init];
    if ([_captureSession canAddOutput:captureMetadataOutput]) {
        [_captureSession addOutput:captureMetadataOutput];
    }
    dispatch_queue_t dispatchQueue;
    dispatchQueue = dispatch_queue_create("myQueue", NULL);
    [captureMetadataOutput setMetadataObjectsDelegate:self queue:dispatchQueue];
    captureMetadataOutput.metadataObjectTypes =@[AVMetadataObjectTypeQRCode];
    [captureMetadataOutput setRectOfInterest:CGRectMake((ScreenWidth*0.475)/ScreenHeight,((ScreenWidth-ScreenHeight*0.475)/2)/ScreenWidth,ScreenHeight*0.475/ScreenHeight,ScreenHeight*0.400/ScreenWidth)];
    _videoPreviewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:_captureSession];
    [_videoPreviewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
    [_videoPreviewLayer setFrame:CGRectMake(0, 0,ScreenWidth,ScreenHeight)];
    [Preview.viewPreview.layer addSublayer:_videoPreviewLayer];
    [_captureSession startRunning];
    return YES;
}
-(void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection{
    if (metadataObjects != nil && [metadataObjects count] > 0) {
        AVMetadataMachineReadableCodeObject * metadataObject = [metadataObjects objectAtIndex:0];
        stringValue = metadataObject.stringValue;
        if ([self.sat isEqualToString:@"2"]) {
            [_captureSession stopRunning];
            [_videoPreviewLayer removeFromSuperlayer];
            _captureSession = nil;
            [timer invalidate];
            timer=nil;
            [self performSelectorOnMainThread:@selector(loadOrderVC) withObject:nil waitUntilDone:NO];
            }
        
        if ([self.sat isEqualToString:@"1"]) {
            [self tingdun];
            [self performSelectorOnMainThread:@selector(loadStockVC) withObject:nil waitUntilDone:NO];
            
        }
        if ([self.sat isEqualToString:@"0"]) {
            
            [self tingdun];
            [self performSelectorOnMainThread:@selector(Coupon) withObject:nil waitUntilDone:NO];
            
        }
        
    }
    
}
-(void)tingdun{
    [_captureSession stopRunning];
    _captureSession = nil;
    [timer invalidate];
    timer=nil;
}
-(void)Coupon
{
    if (![snArray containsObject:stringValue]) {
        
        [self requestCouponDetail:stringValue];//不一样的
    }else{
        
       [self performSelector:@selector(loadcoupon) withObject:nil afterDelay:2.0f];
        
    }
}
-(void)loadcoupon{
    [self requestData];
}
//放到对应的coupon数组
-(void)requestCouponDetail:(NSString *)codeStr
{
    if (![snArray containsObject:codeStr]) {
        NSMutableDictionary *params = [NSMutableDictionary new];
        [params setValue:Token forKey:@"tokenId"];
        [params setValue:codeStr forKey:@"sn"];
        NSLog(@"====%@",params);
        [HttpRequest requestData:@"Business/Coupon/Check" params:params success:^(BOOL isSuccess, SeverData *severDataDict) {
            NSLog(@"====%@",severDataDict.dataDict);
            if (isSuccess) {
                if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                    [self snValue:codeStr couponId:[[severDataDict.dataDict objectForKey:@"coupon"]objectForKey:@"couponId"] endDate:[[severDataDict.dataDict objectForKey:@"coupon"]objectForKey:@"endDate"] beginDate:[[severDataDict.dataDict objectForKey:@"coupon"]objectForKey:@"beginDate"] imageUrlFull:[[severDataDict.dataDict objectForKey:@"coupon"]objectForKey:@"imageUrlFull"] price:[[severDataDict.dataDict objectForKey:@"coupon"]objectForKey:@"price"] qty:[[severDataDict.dataDict objectForKey:@"coupon"]objectForKey:@"qty"] title:[[severDataDict.dataDict objectForKey:@"coupon"]objectForKey:@"title"] useLimitAmt:[[severDataDict.dataDict objectForKey:@"coupon"]objectForKey:@"useLimitAmt"] sex:[[severDataDict.dataDict objectForKey:@"member"]objectForKey:@"sex"] userName:[[severDataDict.dataDict objectForKey:@"member"]objectForKey:@"userName"]  phone:[[severDataDict.dataDict objectForKey:@"member"]objectForKey:@"phone"]] ;
                }else
                {
                    NSString *requestResultStr=[severDataDict.dataDict objectForKey:@"ResultString"];
                    [Global showTextHudSub:requestResultStr view:self.view];
                    [self performSelector:@selector(loadcoupon) withObject:nil afterDelay:2.0f];}
            }
            else
            {
                [Global showTextHudSub:@"连接失败" view:self.view];
            }
        }];
    }
}
-(void)snValue:(NSString *)str couponId:(NSString *)couponId endDate:(NSString *)endDate  beginDate:(NSString *)beginDate imageUrlFull:(NSString *)imageUrlFull  price:(NSString *)price qty:(NSString *)qty title:(NSString *)title useLimitAmt:(NSString *)useLimitAmt sex:(NSString *)sex userName:(NSString *)userName phone:(NSString *)phone
{
    if ([_userNameStr isEqualToString:@""]){
        stringValue=@"";
        _userNameStr=userName;
        _sexStr=sex;
        _phoneStr=phone;
        [snArray addObject:str];
        [titleCouponArray addObject:title];
        [priceCouponArray addObject:price];
        [qtyCouponArray addObject:qty];
        [imageUrlCouponArray addObject:imageUrlFull];
        [endDateCouponArray addObject:endDate];
        [useLimitAmtCouponArray addObject:useLimitAmt];
        [beginDateCouponArray addObject:beginDate];
        [couponIdArray addObject:couponId];
        [numberSCANSTOCK1 setTitle: [NSString stringWithFormat:@"%ld", snArray.count] forState:UIControlStateNormal];
        [numberSCANSTOCK1 addTarget:self action:@selector(scanCouponCountBtnClick) forControlEvents:UIControlEventTouchUpInside];
        [self loadcoupon];
}
if ([_userNameStr isEqualToString:userName]) {
   if (![snArray containsObject:str]){
            stringValue=@"";
            _userNameStr=userName;
            _sexStr=sex;
            _phoneStr=phone;
            [snArray addObject:str];
            [titleCouponArray addObject:title];
            [priceCouponArray addObject:price];
            [qtyCouponArray addObject:qty];
            [imageUrlCouponArray addObject:imageUrlFull];
            [endDateCouponArray addObject:endDate];
            [useLimitAmtCouponArray addObject:useLimitAmt];
            [beginDateCouponArray addObject:beginDate];
            [couponIdArray addObject:couponId];
            [numberSCANSTOCK1 setTitle: [NSString stringWithFormat:@"%ld", snArray.count] forState:UIControlStateNormal];
            [numberSCANSTOCK1 addTarget:self action:@selector(scanCouponCountBtnClick) forControlEvents:UIControlEventTouchUpInside];
            [self loadcoupon];
}
}else{
 [self performSelector:@selector(loadcoupon) withObject:nil afterDelay:2.0f];
}
}
-(void)loadStockVC
{
    if (![scanStockResultArray containsObject:stringValue]) {
        [self requestItemDetail:stringValue];//不一样的
        
    }else{
        
        [self performSelector:@selector(loadStockVCr) withObject:nil afterDelay:2.0f];
        
    }
}
-(void)loadStockVCr{
    
    if (howArray .count>0) {
        for (int i=0; i<scanStockResultArray.count; i++) {
            NSString *codeStr = [scanStockResultArray objectAtIndex:i];
            NSString *how = [howArray objectAtIndex:i];
            if ([codeStr isEqualToString:stringValue] ) {
                double howd;
                howd=[how doubleValue];
                howd++;
                [howArray replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%.f", howd]];
                }
        }
    }
    [self requestData];
}

//放到对应的数组
-(void)requestItemDetail:(NSString *)codeStr
{
    if (![scanStockResultArray containsObject:codeStr]) {
        NSMutableDictionary *params = [NSMutableDictionary new];
        [params setValue:Token forKey:@"tokenId"];
        [params setValue:codeStr forKey:@"pid"];
        [HttpRequest requestData:@"Product/Detail" params:params success:^(BOOL isSuccess, SeverData *severDataDict) {
                     NSLog(@"====%@",severDataDict.dataDict);
            if (isSuccess) {
                if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                    
                    NSMutableArray*specList=[severDataDict.dataDict objectForKey:@"specList"];
                    if (specList.count>0) {
                        
                        
                        for (int i=0; i<specList.count; i++) {
                            
                            NSString *codeStr = [[specList objectAtIndex:i]objectForKey:@"specId"];
                            
                            if ([codeStr isEqualToString:[severDataDict.dataDict objectForKey:@"currentSpecId"]] ) {
                                
                                specName=[specList[i]objectForKey:@"specName"];
                                }}
                        
                    }else{
                        specName=@"";
                        }
                    if ([[severDataDict.dataDict objectForKey:@"currentSpecId"]isEqualToString:@""]) {
                        specName=@"";
                    }
                    
                    [self setScanStockStringValue:stringValue urlStr:[[severDataDict.dataDict objectForKey:@"imageList"][0] objectForKey:@"imageUrlFull"] typeStr:[severDataDict.dataDict objectForKey:@"itemType"]  priceStr:[severDataDict.dataDict objectForKey:@"salePrice"]  itemIdStr:[severDataDict.dataDict objectForKey:@"itemId"] itemNameStr:[severDataDict.dataDict objectForKey:@"itemName"]  currentSpecId:[severDataDict.dataDict objectForKey:@"currentSpecId"] specNameStr:specName  ItemCodeStr:[severDataDict.dataDict objectForKey:@"itemCode"] ];
                    
                }else
                {
                    NSString *requestResultStr=[severDataDict.dataDict objectForKey:@"ResultString"];
                    [Global showTextHudSub:requestResultStr view:self.view];
                     [self performSelector:@selector(loadStockVCr) withObject:nil afterDelay:2.0f];
                    
                }
            }
            else
            {
                [Global showTextHudSub:@"连接失败" view:self.view];
            }
        }];
    }
}
-(void)setScanStockStringValue:(NSString *)str urlStr:(NSString *)urlStr typeStr:(NSString *)typeStr  priceStr:(NSString *)priceStr itemIdStr:(NSString *)itemIdStr  itemNameStr:(NSString *)itemNameStr currentSpecId:(NSString *)currentSpecId specNameStr:(NSString *)specNameStr ItemCodeStr:(NSString *)ItemCodeStr

{
    if (![scanStockResultArray containsObject:str]) {
        stringValue=@"";
        [scanStockResultArray addObject:str];
        [itemUrlArray addObject:urlStr];
        [itemPriceArray addObject:priceStr];
        [itemNameArray addObject:itemNameStr];
        [itemidArray addObject:itemIdStr];
        [itemCodeArray addObject:ItemCodeStr];
        [currentSpecIdArray addObject:currentSpecId];
        [specNameArray addObject:specNameStr];
        [howArray addObject:@"1"];
        NSNumber *sum = [howArray valueForKeyPath:@"@sum.floatValue"];
        [numberSCANSTOCK1 setTitle: [NSString stringWithFormat:@"%@", sum] forState:UIControlStateNormal];
        [numberSCANSTOCK1 addTarget:self action:@selector(scanStockCountBtnClick) forControlEvents:UIControlEventTouchUpInside];
        [self performSelector:@selector(loadStockVCr) withObject:nil afterDelay:2.0f];
}
}
-(void)loadOrderVC
{
    OrderDetailViewController *detailViewController = [[OrderDetailViewController alloc] init];
    detailViewController.orderId=stringValue;
    [self.navigationController pushViewController:detailViewController animated:YES];
    
}
-(void)scanCouponCountBtnClick
{
    [_captureSession stopRunning];
    _captureSession = nil;
    [timer invalidate];
    timer=nil;
    CouponCheckViewController*detailViewController = [[CouponCheckViewController alloc] init];
    detailViewController.mDelegate=self;
    detailViewController.titleArray=titleCouponArray;
    detailViewController.priceArray=priceCouponArray;
    detailViewController.beginDateArray=beginDateCouponArray;
    detailViewController.qtyArray=qtyCouponArray;
    detailViewController.endDateArray=endDateCouponArray;
    detailViewController.imageUrlArray=imageUrlCouponArray;
    detailViewController.useLimitAmtArray=useLimitAmtCouponArray;
    detailViewController.snArray=snArray;
    detailViewController.couponIdArray=couponIdArray;
    detailViewController.phone=_phoneStr;
    detailViewController.sex=_sexStr;
    detailViewController.userName=_userNameStr;
    [self.navigationController pushViewController:detailViewController animated:YES];
}
-(void)scanStockCountBtnClick
{
    [_captureSession stopRunning];
    _captureSession = nil;
    [timer invalidate];
    timer=nil;
    InventoryViewController*detailViewController = [[InventoryViewController alloc] init];
    detailViewController.mDelegate=self;
    detailViewController.itemCodeArray=itemCodeArray;
    detailViewController.itemNameArray=itemNameArray;
    detailViewController.itemUrlArray=itemUrlArray;
    detailViewController.itemidArray=itemidArray;
    detailViewController.specNameArray=specNameArray;
    detailViewController.itemPriceArray=itemPriceArray;
    detailViewController.currentSpecIdArray=currentSpecIdArray;
    detailViewController.howArray=howArray;
    [self.navigationController pushViewController:detailViewController animated:YES];
    
}
-(void)stopReading{
    [_captureSession stopRunning];
    _captureSession = nil;
    [_videoPreviewLayer removeFromSuperlayer];
}
-(void)loadingtitle{
    [theLampBtn removeFromSuperview];
    [backButton removeFromSuperview];
    [searchView removeFromSuperview];
    theLampBtn = [[UIButton alloc] initWithFrame:CGRectMake(ScreenWidth-45, 27.5, 30, 30)];
    [theLampBtn setImage:[UIImage imageNamed:@"shanguangdeng_normal"] forState:UIControlStateNormal];
    [theLampBtn addTarget:self action:@selector(theLampBtn) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:theLampBtn];
    UIImage* backImage = [UIImage imageNamed:@"fanhui"];
    CGRect backframe = CGRectMake(12.5,27.5,30,30);
    backButton= [[UIButton alloc] initWithFrame:backframe];
    [backButton setBackgroundImage:backImage forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(BackAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:backButton];
    searchView=[[UIView alloc]initWithFrame:CGRectMake(45, 25, ScreenWidth-95, 35)];
    searchView.backgroundColor=zuiqianhuiColor;
    searchView.backgroundColor=[UIColor colorWithRed:222/255.0 green:222/255.0 blue:222/255.0 alpha:1];
    searchView.alpha=0.69;
    UIButton *theLampBtn1 = [[UIButton alloc] initWithFrame:CGRectMake( 5, 5, 25, 25)];
    [theLampBtn1 setImage:[UIImage imageNamed:@"sousuo"] forState:UIControlStateNormal];
    [searchView addSubview:theLampBtn1];
    [self.view addSubview:searchView];
    searchTextField = [[UITextField alloc] initWithFrame:CGRectMake(theLampBtn1.right,0, ScreenWidth*400/750,35)];
    [searchTextField setBorderStyle:   UITextBorderStyleNone]; //外框类型
    searchTextField.placeholder = @" 请输入产品编码"; //默认显示的字
    searchTextField.font = [UIFont systemFontOfSize: 14];
    searchTextField.tag=22;
    searchTextField.keyboardType = UIKeyboardTypeDecimalPad;
    searchTextField.returnKeyType = UIReturnKeyDone;
    searchTextField.clearButtonMode = UITextFieldViewModeWhileEditing; //编辑时会出现个修改X
    searchTextField.delegate = self;
    [searchView addSubview:searchTextField];
    UIView* myToolBar=[[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, viewheight)];
    myToolBar.backgroundColor=jianpancolor;
    UIButton*  tubtnDone=[[UIButton alloc]initWithFrame:CGRectMake(logoX,logoY, logoheight, logowidth)];
    [tubtnDone setImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
    [tubtnDone addTarget:self action:@selector(OnTapDone) forControlEvents:UIControlEventTouchUpInside];
    [myToolBar addSubview:tubtnDone];
    UIButton*btnDone111=[[UIButton alloc]initWithFrame:CGRectMake(myToolBar.frame.size.width - 55, 12, 40, 16)];
    [btnDone111 setTitle:@"确定" forState:UIControlStateNormal];
    [btnDone111 setTitleColor:jianpancolor1 forState:UIControlStateNormal];
    btnDone111 .titleLabel .font=[UIFont systemFontOfSize:16];
    [btnDone111 addTarget:self action:@selector(OnTapDone) forControlEvents:UIControlEventTouchUpInside];
    [myToolBar addSubview:btnDone111];
    myToolBar.alpha=alp;
    UIButton* dabtn=[[UIButton alloc]initWithFrame:CGRectMake(myToolBar.frame.size.width-60, 0, 60, 40)];
    [dabtn addTarget:self action:@selector(OnTapDone) forControlEvents:UIControlEventTouchUpInside];
    [myToolBar addSubview:dabtn];
    searchTextField.inputAccessoryView = myToolBar;
    }
- (void)showAlertWait
{
    alt = [[UIAlertView alloc] initWithTitle:@"网络不稳定哦 ！" message:@"请确认网络" delegate:self cancelButtonTitle:nil otherButtonTitles: nil];
    [alt show];
    
    [self performSelector:@selector(hideAlert) withObject:nil afterDelay:3.0f];
    
}
- (void)showAlertMessage:(NSString *)msg
{
    alt = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:msg delegate:nil cancelButtonTitle:nil otherButtonTitles: nil];
    [alt show];
    
    [self performSelector:@selector(hideAlert) withObject:nil afterDelay:5.0f];
}
- (void)hideAlert
{
    if (alt != nil)
    {
        [alt dismissWithClickedButtonIndex:0 animated:YES];
        alt = nil;
    }
}

@end
